<?php

namespace IDock\Insurance\ACIC\Request;

use Exception;
use IDock\Insurance\ACIC\ACICEnums;
use IDock\Insurance\ACIC\Response\UnderwritingResponse;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

/**
 * 核保接口
 */
class UnderwritingRequest extends AllACICRequest
{
    protected $code = 'V01';

    protected $response = UnderwritingResponse::class;

    protected $urlTip = '核保';

    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;

    /**
     * @return array
     * @throws Exception
     */
    public function generate(): array
    {
        $data = [
            'Applicant' => $this->getRelatedInfo($this->visitor->getApplicantVisitor(), 'applicant'),
            'Insured' => $this->getRelatedInfo($this->visitor->getInsuredVisitor(), 'insured'),
            'Owner' => $this->getRelatedInfo($this->visitor->getOwnerVisitor(), 'owner'),
            'CheckItem' => $this->getVehicle(),
            'ApplicationList' => ['Application' => $this->getApplication()],
            'CoverageList' => ['CoverageItem' => PremiumInquiryRequest::getCoverageList($this->visitor)],
            'Taxation' => $this->getTaxation(),
            'SpecifiedDriver' => '',
            'SZPlateInfo' => '',
            'RealNameCheck' => '',
            'SalerNo' => '',
        ];

        if (!$data['CoverageList'] or !count($data['CoverageList']['CoverageItem'])) {
            unset($data['CoverageList']);
        }

        //车上设备
        if ($this->visitor->getDeviceList()) {
            $data['DeviceList'] = ['DeviceItem' => PremiumInquiryRequest::getDeviceList($this->visitor->getDeviceList())];
        }

        return $data;
    }

    /**
     * 车辆信息
     * @return array
     */
    private function getVehicle(): array
    {
        $vehicleVisitor = $this->visitor->getVehicleVisitor();

        $motorTypeCode = '11';

        $carKindCode = $vehicleVisitor->carKindCode;

        if ($carKindCode == '100') {
            if ($vehicleVisitor->vehicleSeat < 6) {
                $motorTypeCode = '11';
            } else {
                $motorTypeCode = '12';
            }
        }

        if ($carKindCode == '200' or $carKindCode == '210') {
            if ($vehicleVisitor->vehicleTonnage < 2000) {
                $motorTypeCode = '21';
            }
            if ($vehicleVisitor->vehicleTonnage >= 2000 and $vehicleVisitor->vehicleTonnage < 5000) {
                $motorTypeCode = '22';
            }

            if ($vehicleVisitor->vehicleTonnage >= 5000 and $vehicleVisitor->vehicleTonnage < 10000) {
                $motorTypeCode = '23';
            }
            if ($vehicleVisitor->vehicleTonnage >= 10000) {
                $motorTypeCode = '24';
            }
        }
        $usageTypeCode = '';

        $useNatureCode = $vehicleVisitor->useNatureCode . $vehicleVisitor->attachNature;

        if ($useNatureCode == '0101') {
            $usageTypeCode = '210';
        }
        if ($useNatureCode == '0102') {
            $usageTypeCode = '220';
        }
        if ($useNatureCode == '0103') {
            $usageTypeCode = '230';
        }

        return [
            'LicensePlateNo' => $vehicleVisitor->licenseNo,
            'MotorTypeCode' => $motorTypeCode,
            'MotorUsageTypeCode' => $usageTypeCode,
            'FirstRegisterDate' => $vehicleVisitor->firstRegisterDate,
            'VIN' => $vehicleVisitor->vin,
            'EngineNo' => $vehicleVisitor->engineNo,
            'Model' => $vehicleVisitor->vehicleModelCode,
            'ReplacementValue' => $vehicleVisitor->vehiclePrice,
            'ChangedVehlValue' => $vehicleVisitor->negotiatedValue ?: $vehicleVisitor->actualValue,
            'TransferDate' => $vehicleVisitor->transferDate,
            'BrandType' => '',
            'DisplaceMent' => $vehicleVisitor->vehicleExhaust,
            'Power' => $vehicleVisitor->power,
            'Whole_Weight' => $vehicleVisitor->wholeWeight,
            //车队标识
            'FleetFlag' => $this->visitor->getExtInfo('FleetFlag', '0'),
            //车队号
            'FleetNo' => $this->visitor->getExtInfo('FleetNo', ''),
            //进口车
            'IpmORLoc' => array_search($vehicleVisitor->vehicleImport, ACICEnums::$importFlag),
            //外地车标志
            'EcdemicVehicleFlag' => $this->visitor->getExtInfo('EcdemicVehicleFlag', '0'),
            //
            'CarName' => $vehicleVisitor->vehicleName,
            'RatedPassengerCapacity' => $vehicleVisitor->vehicleSeat,
            'Tonnage' => (int)$vehicleVisitor->vehicleTonnage,
            'TonnageEx' => (int)$vehicleVisitor->vehicleTonnage / 1000,
            'CSeat' => $vehicleVisitor->vehicleSeat,
            'LoanVehicleFlag' => (int)$this->visitor->getExtInfoVisitor()->isLoanCar,
        ];
    }

    /**
     * 保单信息
     * @return array
     */
    private function getApplication(): array
    {
        $applicationList = [];

        //商业险
        if ($this->visitor->getBiStartData()) {
            $applicationList[] = [
                'ProdNo' => '0333',
                'LastPolicyNo' => '',
                'BillDate' => date('Y-m-d'),
                'EffectiveDate' => $this->visitor->getBiStartData(),
                'ExpireDate' => $this->visitor->getBiEndData(),
                'AreaCode' => $this->visitor->getExtInfo('AreaCode'),

                'QueryNo' => $this->visitor->getUnderwritingVisitor()->biInquiryNo,

                'AgentCode' => $this->visitor->getExtInfo('AgentCode'),
                'AgentContract' => $this->visitor->getExtInfo('AgentContract'),
                'ExpectDiscount' => $this->visitor->getExtInfoVisitor()->expectedDiscount,
                //'SpecialContact' => implode('@', $this->visitor->getUnderwritingVisitor()->agreement),
                'PayURL' => '',
                'NewFuelVhlFlag' => $this->visitor->getVehicleVisitor()->isNewEnergy,
            ];
        }

        //交强险
        if ($this->visitor->getCiStartData()) {
            $applicationList[] = [
                'ProdNo' => '0330',
                'LastPolicyNo' => '',
                'BillDate' => date('Y-m-d'),
                'EffectiveDate' => $this->visitor->getCiStartData(),
                'ExpireDate' => $this->visitor->getCiEndData(),
                'AreaCode' => $this->visitor->getExtInfo('AreaCode'),

                'QueryNo' => $this->visitor->getUnderwritingVisitor()->ciInquiryNo,

                'AgentCode' => $this->visitor->getExtInfo('AgentCode'),
                'AgentContract' => $this->visitor->getExtInfo('AgentContract'),
                'ExpectDiscount' => $this->visitor->getExtInfoVisitor()->expectedDiscount,
                //'SpecialContact' => implode('@', $this->visitor->getUnderwritingVisitor()->agreement),
                'PayURL' => '',
                'NewFuelVhlFlag' => $this->visitor->getVehicleVisitor()->isNewEnergy,
            ];
        }

        return $applicationList;
    }

    /**
     * 险种信息
     * @return array
     */
    private function getCoverageList(): array
    {
        $coverageList = [];

        /*** @var PremiumCoverageVisitor $coverageVisitor */
        foreach ($this->visitor->getCoverageVisitorList() as $coverageVisitor) {

            $coverage = $coverageVisitor->coverageCode;

            //剔除交强险代码
            if ($coverage == 'C01001') {
                continue;
            }

            //新能源险种变换
            $type = substr($coverage, '1', '1');

            if ($type == '1' and !in_array($coverage, ['C16001', 'C16002', 'C16003', 'C16004', 'C16005'])) {
                $coverage = 'C0' . substr($coverage, '2', 4);
            }

            $item = [
                'CoverageCode' => ACICEnums::$coverageCode[$coverage],
                'SumLimit' => $coverageVisitor->amount,
                'FreeFlag' => '1',
                'FreeNum' => '',
                'DayFee' => '0',
                'DaySeatNum' => '0',
                'GlassType' => '',
                'DRSRate' => '0',
                'AbRate' => '',
                'ServiceCount' => '',
                'LimitTimes' => ''
            ];

            //车损险绝对免赔额
            if ($coverage == 'C02001' and $coverageVisitor->deductionLimit) {
                $item['FreeNum'] = ACICEnums::$deductionLimit[$coverageVisitor->deductionLimit];
            }

            //指定修理厂险修理期间费用补偿险单位保额
            if ($coverage == 'C02003' or $coverage == 'C12003') {
                $item['DayFee'] = $coverageVisitor->unitAmount;
                $item['DaySeatNum'] = $coverageVisitor->quantity;
            }

            //乘客险座位数
            if ($coverage == 'C05001') {
                $item['DayFee'] = $coverageVisitor->unitAmount;
                $item['DaySeatNum'] = $this->visitor->getVehicleVisitor()->vehicleSeat - 1;
            }
            //指定修理厂费率
            if ($coverage == 'C02003') {
                $item['DRSRate'] = $coverageVisitor->rate;
            }

            if ($coverageVisitor->deductionRate) {
                $item['AbRate'] = (string)$coverageVisitor->deductionRate / 100;
            }

            $coverageList[] = $item;
        }

        return $coverageList;
    }

    /**
     * 关系人信息
     * @param $relatedIVisitor
     * @param string $type
     * @return array
     */
    private function getRelatedInfo($relatedIVisitor, string $type = ''): array
    {
        $data = [
            'Name' => $relatedIVisitor->name,
            'CertificateType' => $relatedIVisitor->certificateTypeCode,
            'CertificateNo' => $relatedIVisitor->certificateNo,
            'Contact' => $relatedIVisitor->name,
            'Phone' => $relatedIVisitor->mobile,
            'Address' => $relatedIVisitor->address,
            'OrganizationType' => '',
            'Age' => '',
            'Gender' => '',
            'Email' => $relatedIVisitor->email,
            //与车辆关系
            'VchlOwnership' => '2',
        ];

        //单位性质
        if ($relatedIVisitor->typeCode == 'R1') {
            $data['OrganizationType'] = '001';
        } else {
            $data['OrganizationType'] = '100';
        }

        if ($type == 'owner') {
            $data['OwnerName'] = $data['Name'];
            unset($data['Name']);
        }

        return $data;
    }

    private function getTaxation(): array
    {
        $carTaxVisitor = $this->visitor->getCarTaxVisitor();
        $taxTypeCode = $carTaxVisitor->taxTypeCode;

        //完税
        if ($taxTypeCode == 'T02') {
            $taxPaid = [
                'TaxDepartmentCode' => $carTaxVisitor->taxDepartmentCode,
                'TaxDepartment' => $carTaxVisitor->taxDepartment,
                'TaxDocumentNumber' => $carTaxVisitor->taxDocumentNumber,
                'TaxDocumentDate' => $carTaxVisitor->taxDocumentDate,
                'TaxPaidAreaCode' => $carTaxVisitor->taxPaidAreaCode,
            ];
        }

        //减税
        if ($taxTypeCode == 'T03' or $taxTypeCode == 'T04') {
            $taxDerate = [
                'DeductionDueCode' => ACICEnums::$taxReductionReasonCode[$carTaxVisitor->taxReductionReasonCode],
                'DeductionDueType' => $carTaxVisitor->taxReductionCode,
                'DeductionDueProportion' => $carTaxVisitor->taxFreeRate,
                'Deduction' => $carTaxVisitor->taxExemption,
                'DeductionDocumentNumber' => $carTaxVisitor->taxDocumentNumber,
                'TaxDepartmentCode' => $carTaxVisitor->taxDepartmentCode,
                'TaxDepartment' => $carTaxVisitor->taxDepartment,
            ];
        }

        return [
            'TaxTermTypeCode' => '08',
            'TaxConditionCode' => ACICEnums::$taxTypeCode[$this->visitor->getCarTaxVisitor()->taxTypeCode],
            'TaxRegistryNumber' => $carTaxVisitor->taxDocumentNumber,
            'TaxPayerName' => $this->visitor->getOwnerVisitor()->name,
            'TaxPayerIdentificationCode' => $this->visitor->getOwnerVisitor()->certificateNo,
            'DeclareDate' => date('Y-m-d'),
            'CurrentTaxDue' => [
                'TaxLocationCode' => $this->visitor->getExtInfo('AreaCode'),
                'TaxStartDate' => $carTaxVisitor->taxStartDate,
                'TaxEndDate' => $carTaxVisitor->taxEndDate,
                'TaxUnitTypeCode' => '',
                'UnitRate' => '',
                'AnnualTaxAmount' => '',
                'Paid' => $taxPaid ?? [],
                'Derate' => $taxDerate ?? [],
                'TaxDue' => '',
                'ExceedDate' => '',
                'ExceedDaysCount' => '',
                'OverDue' => '',
                'TotalAmount' => '',
            ],
            'Declare_Status_IA' => ''
        ];
    }

}
